// home.js
var util = require('../../utils/util.js')
var order = ['red', 'yellow', 'blue', 'green', 'red']
Page({
    data: {
        imgUrls: [
            'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
            'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
            'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
        ],
        indicatorDots: true,
        autoplay: true,
        interval: 3000,
        duration: 500,
        diancan: "tab-button-selected",
        waimai: "tab-button",
        categories: [],
        listdata: [],
        statu: 0,
        //条件字段
        store_type: 'in',
        keyword: '',
        category_id: 0,
        open: false,
        //侧边栏条件
        iscard: '0',
        isparking: '0',
        iswifi: '0',
        istakeaway: '0',
        isroom: '0',
        page_offset: 0,
        page_size: 10,
        isLoading: false,
        is_load_all: false,
        star_count: [0, 0, 0, 0, 0],
        latitude: 0,
        longitude: 0,
        default_logo: '../../resources/img/default_logo.png'
    },

    tapMove: function (e) {
        this.setData({
            scrollTop: this.data.scrollTop + 10
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log("on load")
        var that = this
        that.loadTopData()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.setData({
            page_offset: 0
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            page_offset: 0
        })
        console.log("on show")
        var that = this
        this.getUserLocation(function () {
            that.loadStoreList()
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },
    /**
     * 获取用户地理位置信息
     */
    getUserLocation: function (cb) {
        var that = this
        if (this.data.longitude && this.data.latitude){
            if (cb) cb([])
        }else{
            wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                    var latitude = res.latitude
                    var longitude = res.longitude
                    that.setData({
                        longitude: longitude,
                        latitude: latitude
                    })
                    if (cb) cb(res)
                },
                fail: function () {
                    wx.showToast({
                        title: '获取GPS信息失败!',
                        duration:2000
                    })
                    if (cb) cb(res)
                }
            })
        }

    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },


    /**
     * 加载数据源
     */
    loadTopData: function () {
        var that = this
        getApp().http.request({
            url:'/api/v1/index/top',
            method: 'GET',
            data: {},
            dataType: 'json',
            success: function (res) {
                console.log(res.data.data)
                if (res.data.code == '200') {
                    that.setData({
                        categories: res.data.data.categories,
                        listdata: res.data.data.list,
                        imgUrls: res.data.data.banner,
                        category_id: res.data.data.categories[0].id
                    })
                }
            }
        })
    },
    /**
     * 分类选择事件 点餐|外卖
     */
    selectClick: function (event) {
        this.resetPage();
        if (event.currentTarget.dataset.statu == "tab-button") {
            if (event.currentTarget.id == "dianCan") {
                this.setData({
                    diancan: "tab-button-selected",
                    waimai: "tab-button",
                    store_type: "in"
                })
            } else {
                this.setData({
                    diancan: "tab-button",
                    waimai: "tab-button-selected",
                    store_type: "out"
                })
            }
            this.loadStoreList()
        }
    },
    /**
     * tab点击事件
     */
    tabClick: function (event) {
        console.log(event)
        this.resetPage();
        this.setData({
            statu: event.currentTarget.dataset.index,
            category_id: event.currentTarget.dataset.id
        })
        this.loadStoreList();
    },
    resetPage:function(){
        this.setData({
            page_offset:0,
            isLoading:false,
            is_load_all:false
        })
    },
    /**
     * 店铺列表详情点击事件
     */
    shop_detail: function (event) {
        console.log(event.currentTarget.dataset.id)
        var id = event.currentTarget.dataset.id

        wx.navigateTo({
            url: "../main/main?id=" + id
        })
    },
    /**
     * 搜索input失去焦点时调用，设置keyword的值
     */
    keywordEvent: function (e) {
        this.setData({
            keyword: e.detail.value
        })
        this.loadStoreList()
    },
    /**
     * 店铺条件搜索函数
     */
    loadStoreList: function () {
        this.setData({
            page_offset: 0
        })
        var path = '/api/v1/index?' + util.objectToString(this.getFilter())
        var that = this
        getApp().http.request({
            url: path, //仅为示例，并非真实的接口地址
            method: 'GET',
            data: {},
            dataType: 'json',
            success: function (res) {
                console.log(res)
                if (res.data.msg != 'request:ok') {

                    that.setData({
                        categories: res.data.data.categories,
                        listdata: res.data.data.list
                    })
                }
            },
            fail: function () {

            }
        })
    },
    tap_ch: function (e) {
        if (this.data.open) {
            this.setData({
                open: false
            });
        } else {
            this.setData({
                open: true
            });
        }
    },
    conditionEvent: function (e) {
        var status = '0';
        if (e.currentTarget.dataset.conditionstatus == '1') {
            status = '0';
        } else {
            status = '1';
        }
        var that = this
        switch (e.currentTarget.dataset.conditionname) {
            case 'iscard':
                that.setData({
                    iscard: status
                })
                break;
            case 'isparking':
                that.setData({
                    isparking: status
                })
                break;
            case 'iswifi':
                that.setData({
                    iswifi: status
                })
                break;
            case 'istakeaway':
                that.setData({
                    istakeaway: status
                })
                break;
            case 'isroom':
                that.setData({
                    isroom: status
                })
                break;
            default:
                break;
        }
    },
    /**
     * 筛选条件选择完毕
     */
    filtrateComplete: function () {
        this.setData({
            open: false
        });
    },
    /**
     * 筛选条件重置
     */
    filtrateReset: function () {
        this.setData({
            iscard: '0',
            isparking: '0',
            iswifi: '0',
            istakeaway: '0',
            isroom: '0'
        })
    },
    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
        }
        return {
            title: '人人点餐',
            path: '/pages/home/home',
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },
    bindscrolltolower: function(){
        var that = this
        that.loadPageData()
    },
    getFilter: function (){
        var that = this
        return {
            'type': that.data.store_type,
            'keyword': that.data.keyword,
            'category_id': that.data.category_id,
            'offset': that.data.page_offset * that.data.page_size,
            'is_parking': that.data.isparking,
            'is_card': that.data.iscard,
            'is_wifi': that.data.iswifi,
            'is_takeaway': that.data.istakeaway,
            'is_room': that.data.isroom,
            "_lat": that.data.latitude,
            "_lng": that.data.longitude
        }
    },
    loadPageData: function () {
        var that = this
        if (!that.data.isLoading && !that.data.is_load_all) {
            that.setData({
                page_offset: that.data.page_offset + 1,
                isLoading: true
            })
            var path = '/api/v1/index?' + util.objectToString(this.getFilter())
            getApp().http.request({
                url: path, //仅为示例，并非真实的接口地址
                method: 'GET',
                data: {},
                dataType: 'json',
                success: function (res) {
                    console.log(res)
                    if (res.data.data.list.length > 0) {
                        var tmp_listdata = that.data.listdata
                        for (var i = 0; i < res.data.data.list.length; i++) {
                            tmp_listdata.push(res.data.data.list[i])
                        }
                        that.setData({
                            categories: res.data.data.categories,
                            listdata: tmp_listdata,
                            isLoading: false
                        })
                    } else {
                        if (!that.data.is_load_all) {
                            wx.showToast({
                                title: '没有更多数据了',
                                duration:2000
                            })
                            that.setData({
                                is_load_all: true,
                                isLoading: false
                            })
                        }
                    }
                },
                fail: function () {

                }
            })
        }
    }
})